import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import style from './styles.css';
import { LeftPage, LeftTopBox, LeftBottomBox } from './style';
import { BorderBox12, BorderBox13 } from '@jiaminghi/data-view-react';
import { ModuleTitle } from '../../style/globalStyledSet';

const DataGovernance = ({ data }) => {
  const trendChartRef = useRef(null);// 趋势图 DOM 引用
  const compareChartRef = useRef(null);// 对比图 DOM 引用

  useEffect(() => {
    if (!data) return;

    // 1. 趋势图
    const trendChart = echarts.init(trendChartRef.current);
    trendChart.setOption({
      // 提示框配置
      tooltip: {
        trigger: 'axis',
        //自定义提示框格式
        formatter: function (params) {
          let result = `${params[0].name}<br/>`;
          params.forEach(param => {
            const seriesName = param.seriesName;
            const value = param.value;
            result += `${seriesName}: ${(value * 100).toFixed(2)}%<br/>`;
          });
          return result;
        }
      },
      // 图例配置 垂直滚动图例
      legend: {
        type: 'scroll',
        orient: 'horizontal',
        data: [
          ...data.departments.map(dept => dept + '-器件入库率'),
          ...data.departments.map(dept => dept + '-电路维护率')
        ],
        textStyle: {  // 图例文本样式配置
          color: '#FFFFFF',          // 字体颜色（白色）
        },
        pageTextStyle: {  // 分页按钮文字样式
          color: '#CCCCCC'
        }
      },
      // 图表布局
      grid: {
        left: '3%',
        right: '3%',
        bottom: '3%',
        containLabel: true,
      },
      // X轴(时间)
      xAxis: {
        type: 'category',
        data: data.months,
        axisLabel: {
          color: '#bad9ed',
        }
      },
      // Y轴(百分比)
      yAxis: {
        type: 'value',
        min: 0.6,
        max: 1,
        axisLabel: {
          color: '#bad9ed',
          formatter: function (value) {
            // 更安全的百分比格式化
            return (Math.round(value * 100 * 100) / 100) + '%';  // 保留两位小数
          }
        }
      },
      // 数据系列
      series: [
        ...data.componentStorage.trendSeries,
        ...data.circuitMaintenance.trendSeries
      ]
    });

    // 2. 对比图
    const compareChart = echarts.init(compareChartRef.current);
    compareChart.setOption({
      // 提示框配置
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          let result = `${params[0].name}<br/>`;
          params.forEach(param => {
            const seriesName = param.seriesName;
            const dataIndex = param.dataIndex;
            const dataSet = seriesName === '器件入库率' ?
              data.componentStorage.byDepartment[dataIndex] :
              data.circuitMaintenance.byDepartment[dataIndex];
            result += `${seriesName}: ${(param.value * 100).toFixed(2)}%<br/>`;
            if (seriesName === '器件入库率') {
              result += `已入库: ${dataSet.completed}件<br/>总数: ${dataSet.total}件<br/>`;
            } else {
              result += `已维护: ${dataSet.completed}个<br/>总数: ${dataSet.total}个<br/>`;
            }
          });
          return result;
        },
        axisPointer: {
          type: 'shadow'
        }
      },
      // 图例配置
      legend: {
        data: ['器件入库率', '电路维护率'],
        textStyle: {
          color: '#bad9ed',
        },

      },
      // 图表布局
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      // X轴(时间)
      xAxis: {
        type: 'category',
        data: data.departments,
        axisLabel: {
          color: '#bad9ed',
          // fontSize: 14,
          // fontWeight: 'bold',
          // fontFamily: 'Microsoft YaHei',
          interval: 0,
          rotate: 30
        }
      },
      // Y轴(百分比)
      yAxis: {
        type: 'value',
        min: 0,
        max: 1,
        axisLabel: {
          color: '#bad9ed',
          formatter: function (value) {
            // 更安全的百分比格式化
            return (Math.round(value * 100 * 100) / 100) + '%';  // 保留两位小数
          }
        }
      },
      // 数据系列
      series: [
        {
          name: '器件入库率',
          type: 'bar',
          data: data.componentStorage.byDepartment.map(item => item.value),
          itemStyle: {
            color: '#1890ff'
          }
        },
        {
          name: '电路维护率',
          type: 'bar',
          data: data.circuitMaintenance.byDepartment.map(item => item.value),
          itemStyle: {
            color: '#13c2c2'
          }
        },
      ]
    });

    return () => {
      trendChart.dispose(); // 清理趋势图实例
      compareChart.dispose(); // 清理对比图实例
    };
  }, [data]);// 依赖 data 属性变化

  // style={{
  //   font-size: 60px;
  //   font-weight: bold;
  //   margin-bottom: 20px;
  //   padding-bottom: 10px;
  //   border-bottom: 1px solid #e8e8e8;
  // }}{style['tab-container']}
  return (
    <LeftPage>
      {/* <div className={style['section']}> */}
      {/* <h2 className="section-title">基础数据治理</h2> */}
      <ModuleTitle>
        <i className='iconfont'>&#xe78f;</i>
        <span>基础数据治理</span>
      </ModuleTitle>
      <div className='left-top'>
        <LeftTopBox>
          <BorderBox12 className='left-top-borderBox12'>
            <div className='left-top'>
              <ModuleTitle>
                <span>器件入库率与电路维护率 - 事业部对比</span>
              </ModuleTitle>
              <br />
              <div ref={compareChartRef} className={style['chart']}></div>
            </div>
          </BorderBox12>
        </LeftTopBox>

        <LeftBottomBox>
          <BorderBox13 className='left-bottom-borderBox13'>
            <div className='left-bottom'>
            <br/>
              <ModuleTitle>
                <span>器件入库率与电路维护率趋势</span>
              </ModuleTitle>
              <br/>
              <div ref={trendChartRef} className={style['chart']}></div>
            </div>
          </BorderBox13>
        </LeftBottomBox>
      </div>
      {/* </div> */}
    </LeftPage>
  );
};

export default DataGovernance;